#include <jni.h>
#include <unistd.h>
#include <fcntl.h>
#include <memory.h>

#ifndef AT_CHECK
#define AT_CHECK      0x10000        /* command execution from file is intended, check exec permissions */
#endif

#ifndef AT_EMPTY_PATH
#define AT_EMPTY_PATH		0x1000
#endif


#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT jint JNICALL Java_org_apache_jasper_JspCompilationContext_checkFileExec
  (JNIEnv* env, jclass cls, jstring name){
    int ret, fd;
    int len = env->GetStringLength(name);
    const char* path = env->GetStringUTFChars(name, NULL);
    char* checkPath = new char[len + 1];
    strcpy(checkPath, path);
    checkPath[len] = '\0';

    fd = open(checkPath, O_RDONLY, 0);
    if(fd < 0)
        return -1;

    char arg[] = "";
    char *args[] = { arg, NULL };
    ret = execveat(fd, "", args, NULL, AT_CHECK | AT_EMPTY_PATH);
    if(ret < 0) {
        close(fd);
        return -1;
    }

    close(fd);  
    delete[] checkPath;
    env->ReleaseStringUTFChars(name, path);
    return 0;
}

#ifdef __cplusplus
}
#endif

